/*    This file is part of libepistle.
 *
 *    libepistle is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    libepistle is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with libepistle.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include "err.h"
#include "local.h"

int
local_server(const char *path, int backlog, Err *err)
{
	struct sockaddr_un addr;
	int sock = socket(AF_UNIX, SOCK_STREAM, 0);

	if (sock < 0) {
		err_std(err);
		return -1;
	}

	addr.sun_family = AF_UNIX;

	if (strlen(path) > sizeof(addr.sun_path) - 1) {
		close(sock);
		err->region = err_region_epistle;
		err->code = EPISTLE_ERR_NAME_LEN;
		return -1;
	}

	strcpy(addr.sun_path, path);

	/* It doesn't hurt to unlink before binding */
	unlink(path);

	if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		err_std(err);
		close(sock);
		return -1;
	}

	if (listen(sock, backlog < 0 ? SOMAXCONN : backlog) < 0) {
		err_std(err);
		close(sock);
		unlink(path);
		return -1;
	}

	return sock;
}

int
local_client(const char *path, Err *err)
{
	struct sockaddr_un addr;
	int sock = socket(AF_UNIX, SOCK_STREAM, 0);

	if (sock < 0) {
		err_std(err);
		return -1;
	}

	addr.sun_family = AF_UNIX;

	if (strlen(path) > sizeof(addr.sun_path) - 1) {
		err->region = err_region_epistle;
		err->code = EPISTLE_ERR_NAME_LEN;
		close(sock);
		return -1;
	}

	strcpy(addr.sun_path, path);

	if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
	        err_std(err);
		close(sock);
		return -1;
	}

	return sock;
}
